// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// z [author] rhyme_lph
// r [email]  rhymelph@gmail.com
// f [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/inventory_entity.dart';
import 'package:finance_app/src/entities/ocr_attachment_entity.dart';
import 'package:finance_app/src/entities/product_entity.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/input_formatter_tools.dart';
import 'package:finance_app/src/widgets/button/add_button.dart';
import 'package:finance_app/src/widgets/button/normal_button.dart';
import 'package:finance_app/src/widgets/button/normal_popup_button.dart';
import 'package:finance_app/src/widgets/button/normal_text_button.dart';
import 'package:finance_app/src/widgets/common/tag_widget.dart';
import 'package:finance_app/src/widgets/form/attach_file_form.dart';
import 'package:finance_app/src/widgets/form/boms_number_item_form.dart';
import 'package:finance_app/src/widgets/form/buy_or_sell_form.dart';
import 'package:finance_app/src/widgets/form/form_edit_status_inherited_widget.dart';
import 'package:finance_app/src/widgets/form/inventory_item_form.dart';
import 'package:finance_app/src/widgets/form/inventory_item_widget.dart';
import 'package:finance_app/src/widgets/form/text_area_input_form.dart';
import 'package:finance_app/src/widgets/form/value_select_form.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/form/gst_inclusive_form.dart';
import 'package:finance_app/src/widgets/input/form_input_field.dart';
import 'package:finance_app/src/widgets/switch/normal_switch.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/dashboard/products_services/new_product_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:tuple/tuple.dart';

@RouterMeta(paramName: "newProductPage")
class NewProductPage extends StatefulWidget {
  final bool isPro; // when the pro will need more information.
  final ProductEntity data;
  final String text;
  final int id;
  const NewProductPage({Key key, this.isPro, this.data, this.text, this.id})
      : super(key: key);

  @override
  _NewProductPageState createState() => _NewProductPageState();
}

class _NewProductPageState extends State<NewProductPage>
    with PagePresenter<NewProductPage, NewProductProvider> {
  String get title => provider.id == null
      ? S.current.new_product
      : provider.isEdit == true
          ? S.current.edit_product
          : S.current.product;

  Widget get rightButton => listBuilder<bool>(
        selector: (_, __) => __.isEdit == true || provider.id == null,
        builder: (BuildContext context, bool value, Widget child) =>
            value ? _buildSaveBtn() : _buildPopButton(),
      );

  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
          titleWidget: listBuilder<bool>(
            selector: (_, __) => __.isEdit,
            builder: (BuildContext context, bool value, Widget child) =>
                Text(title),
          ),
          actions: [
            if (widget.isPro == true) rightButton,
          ]);

  Widget _buildPopButton() => listBuilder<Tuple2<bool, int>>(
        selector: (_, __) => Tuple2(__.isEdit, __.menuList.length),
        builder:
            (BuildContext context, Tuple2<bool, int> value, Widget child) =>
                value.item1 == false
                    ? NormalMorePopupButton(
                        onSelect: provider.onSelectMenu,
                        menuList: provider.menuList,
                      )
                    : _buildSaveBtn(),
      );

  Widget _buildSaveBtn() {
    return NormalSaveTextButton(
      onTap: provider.onSave,
    );
  }

  @override
  void initState() {
    provider.initProduct(widget.data, widget.text);
    super.initState();
  }

  @override
  Widget wrapperBody(Widget child) {
    return listBuilder<bool>(
      selector: (_, __) => __.isEdit == true || provider.id == null,
      builder: (BuildContext context, bool value, Widget child) =>
          FormEditStatusInheritedWidget(
        isEdit: value,
        child: child,
      ),
      child: child,
    );
  }

  @override
  Widget get buildWidget => _buildProLayout();

  Widget _buildProLayout() => ListView(
        children: [
          Stack(
            children: [
              listBuilder<bool>(
                selector: (_, __) => __.numberHasError,
                builder: (BuildContext context, bool value, Widget child) =>
                    FromInputField(
                  tip: S.current.product_code,
                  controller: provider.codeController,
                  focusNode: provider.codeFocusNode,
                  hasError: value,
                ),
              ),
              Align(
                alignment: Alignment.centerRight,
                child: listBuilder<bool>(
                  selector: (_, __) => __.isActivate,
                  builder: (BuildContext context, bool value, Widget child) =>
                      value == false
                          ? Container(
                              margin: EdgeInsets.only(
                                  right: getDp(35), top: getDp(20)),
                              child: RedTagWidget(
                                content: S.current.deactivated,
                              ),
                            )
                          : Container(),
                ),
              )
            ],
          ),
          FromInputField(
            tip: S.current.product_name,
            controller: provider.nameController,
            focusNode: provider.nameFocusNode,
          ),
          listBuilder<String>(
            selector: (_, __) => __.unit?.name,
            builder: (BuildContext context, String value, Widget child) =>
                ValueSelectForm(
              title: S.current.unit_of_measurement,
              value: value,
              onTap: provider.onChangeProductUnit,
            ),
          ),
          listBuilder<String>(
            selector: (_, __) => __.categories?.join(','),
            builder: (BuildContext context, String value, Widget child) =>
                ValueSelectForm(
              title: S.current.categoryoptional,
              value: value,
              onTap: provider.onSelectCategory,
            ),
          ),
          FromInputField(
            tip: S.current.barcodeoptional,
            controller: provider.barCodeController,
            focusNode: provider.barCodeFocusNode,
            trailing: PressedOpacityButton(
              onPressed: provider.onCameraBarcode,
              child: SvgPicture.asset(
                A.assetsImagesStyleBarcode_1,
                width: getDp(32),
                height: getDp(32),
                fit: BoxFit.contain,
              ),
            ),
            border: null,
          ),
          listBuilder<bool>(
            selector: (_, __) => __.showSellPrice,
            builder: (BuildContext context, bool value, Widget child) =>
                value == true
                    ? Column(
                        children: [
                          AppSpaces.grayH6,
                          listBuilder<Tuple4<bool, String, String, bool>>(
                            selector: (_, __) =>
                                Tuple4<bool, String, String, bool>(
                                    __.isCheckSellInclusive,
                                    __.sellCurrency?.key,
                                    __.sellGstRate?.displayName,
                                    __.enableSell),
                            builder: (BuildContext context,
                                    Tuple4<bool, String, String, bool> value,
                                    Widget child) =>
                                BuyOrSellForm(
                              title: S.current.sell,
                              isCheckInclusive: value.item1,
                              unit: value.item2 ?? "SGD",
                              gstRate: value.item3,
                              isCheck: value.item4,
                              onChangeCheck: provider.onChangeSell,
                              onChangeCheckInclusive:
                                  provider.onChangeSellInclusive,
                              onChangeUnt: provider.onChangeSellUnit,
                              onChangeGstRate: provider.onChangeSellGstRate,
                              controller: provider.sellPriceController,
                              focusNode: provider.sellFocusNode,
                            ),
                          ),
                        ],
                      )
                    : Container(),
          ),
          listBuilder<bool>(
            selector: (_, __) => __.showBuyPrice,
            builder: (BuildContext context, bool value, Widget child) =>
                value == true
                    ? Column(
                        children: [
                          FormStatusWidget(
                            enable: AppSpaces.grayH6,
                            disable: AppSpaces.grayH05,
                          ),
                          listBuilder<Tuple4<bool, String, String, bool>>(
                            selector: (_, __) =>
                                Tuple4<bool, String, String, bool>(
                                    __.isCheckBuyInclusive,
                                    __.buyCurrency?.key,
                                    __.buyGstRate?.displayName,
                                    __.enableBuy),
                            builder: (BuildContext context,
                                    Tuple4<bool, String, String, bool> value,
                                    Widget child) =>
                                BuyOrSellForm(
                              title: S.current.buy,
                              isCheckInclusive: value.item1,
                              unit: value.item2 ?? "SGD",
                              gstRate: value.item3,
                              isCheck: value.item4,
                              onChangeCheck: provider.onChangeBuy,
                              onChangeCheckInclusive:
                                  provider.onChangeBuyInclusive,
                              onChangeUnt: provider.onChangeBuyUnit,
                              onChangeGstRate: provider.onChangeBuyGstRate,
                              controller: provider.buyPriceController,
                              focusNode: provider.buyFocusNode,
                            ),
                          ),
                        ],
                      )
                    : Container(),
          ),
          FormStatusWidget(
            disable: listBuilder<List<ProductBoms>>(
              selector: (_, __) => List.from(__.bomsList),
              builder: (BuildContext context, List<ProductBoms> value,
                      Widget child) =>
                  Column(children: [
                if (value.length > 0) AppSpaces.grayH05,
                ...List.generate(
                    value.length,
                    (index) => listBuilder<ProductBoms>(
                          selector: (_, __) => __.bomsList[index],
                          builder: (BuildContext context, ProductBoms value,
                                  Widget child) =>
                              NormalFormWrapper(
                            topPadding: getDp(10),
                            bottomPadding: getDp(14),
                            hasBottomBorder: true,
                            child: BomsNumberItemForm(
                              key: ValueKey(index),
                              initialNumber: provider.bomsMap[value.id] ?? 1,
                              title: index == 0
                                  ? S.current.bill_of_materials
                                  : null,
                              onNumberCallback: (data) =>
                                  provider.onUpdateBomNumber(value.id, data),
                              content: value.name,
                            ),
                          ),
                        )),
              ]),
            ),
            enable: Container(),
          ),
          listBuilder<Tuple4<int, String, bool, bool>>(
            selector: (_, __) => Tuple4(
                __.id,
                __.productQuantityController.text,
                __.inventoryEnable,
                __.canEditInventory),
            builder: (BuildContext context,
                    Tuple4<int, String, bool, bool> value, Widget child) =>
                InventoryItemForm(
              id: value.item1,
              canEdit: value.item4,
              onChangeInventory: provider.onChangeInventoryEnable,
              inventoryEnable: value.item3,
              controller: provider.productQuantityController,
              focusNode: provider.productQuantityFocusNode,
              onAdjustInventory: provider.onAdjustInventory,
            ),
          ),
          listBuilder<bool>(
              selector: (_, __) => __.inventoryEnable,
              builder: (BuildContext context, bool value, Widget child) =>
                  value == true ? child : Container(),
              child: FormStatusWidget(
                enable: listBuilder<int>(
                  selector: (_, __) => __.bomsList.length,
                  builder: (BuildContext context, int value, Widget child) =>
                      Column(
                    children: List.generate(
                        value,
                        (index) => listBuilder<ProductBoms>(
                              selector: (_, __) => __.bomsList[index],
                              builder: (BuildContext context, ProductBoms value,
                                      Widget child) =>
                                  PressedOpacityButton(
                                onPressed: () => provider.onChangeBom(index),
                                child: NormalFormWrapper(
                                  topPadding: getDp(10),
                                  bottomPadding: getDp(14),
                                  hasBottomBorder: true,
                                  child: BomsNumberItemForm(
                                    key: ValueKey(index),
                                    initialNumber:
                                        provider.bomsMap[value.id] ?? 1,
                                    title: S.current.bom,
                                    onNumberCallback: (data) => provider
                                        .onUpdateBomNumber(value.id, data),
                                    content: value.name,
                                  ),
                                ),
                              ),
                            )),
                  ),
                ),
                disable: SizedBox(),
              )),
          // FormStatusWidget(
          //   enable: listBuilder<bool>(
          //     selector: (_, __) => __.inventoryEnable,
          //     builder: (BuildContext context, bool value, Widget child) => value
          //         ? Column(
          //             children: [
          //               NormalFormWrapper(
          //                 child: AddButton(
          //                   title: S.current.add_bill_of_material,
          //                   onTap: provider.onAddBillOfMaterial,
          //                 ),
          //               )
          //             ],
          //           )
          //         : SizedBox(),
          //   ),
          //   disable: SizedBox(),
          // ),
          AppSpaces.grayH6,
          TextAreaInputForm(
            title: S.current.product_description_optional,
            controller: provider.productDescController,
            focusNode: provider.productDescFocusNode,
          ),
          NormalFormWrapper(
            child: listBuilder<Tuple2<List<String>, List<OcrAttachmentEntity>>>(
              selector: (_, __) =>
                  Tuple2(List.from(__.files), List.from(__.attachments ?? [])),
              builder: (BuildContext context,
                      Tuple2<List<String>, List<OcrAttachmentEntity>> value,
                      Widget child) =>
                  AttachFileForm(
                onAdd: provider.onAddAttachment,
                files: value.item1,
                onSelectFile: provider.onSelectFile,
                attachments: value.item2,
                onSelectAttachment: provider.onSelectAttachment,
              ),
            ),
          ),
          FormStatusWidget(
            enable: Container(),
            disable: _buildInventoryHistoryWidget(),
          )
        ],
      );

  Widget _buildInventoryHistory(List<InventoryEntity> value) {
    return Column(
      children: value
          .map((e) => PressedOpacityButton(
                onPressed: () => provider.onNavInventoryItem(e),
                child: InventoryItemWidget(
                  time: DateTimeUtils.formatDateTimeString(e.createdAt),
                  unit: 'units',
                  inventory: e.quantity,
                  status: e.typeName,
                  name: '${e.name}',
                ),
              ))
          .toList(),
    );
  }

  Widget _buildInventoryHistoryWidget() {
    if (provider.inventoryEnable == true && provider.id != null)
      return Column(
        children: [
          AppSpaces.grayH6,
          NormalFormWrapper(
            hasBottomBorder: true,
            child: Align(
              alignment: Alignment.centerLeft,
              child: Text(
                S.current.inventory_history,
                style: TextStyle(
                  color: aceDarkGrayColor,
                  fontSize: getSp(12),
                  fontWeight: FontWeight.w400,
                  height: 14 / 12,
                ),
              ),
            ),
          ),
          listBuilder<int>(
            selector: (_, __) => __.inventoryList?.length,
            builder: (BuildContext context, int value, Widget child) =>
                LoadDataWidget<List<InventoryEntity>>(
              value: provider.inventoryList,
              buildWidget: _buildInventoryHistory,
            ),
          ),
        ],
      );
    return Container();
  }
}
